<template>
  <div ref="chartRef" style="height: 300px;"></div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, computed } from 'vue'; // 1. 引入 computed
import * as echarts from 'echarts';

const props = defineProps({
  trendData: { type: Array, required: true },
  recommendedIntake: { type: Number, default: 1500 }
});

const chartRef = ref(null);
let chartInstance = null;

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// --- 【关键修复】 2. 计算 Y 轴最大值 ---
const yAxisMax = computed(() => {
  // 找出数据中的最大值
  const dataMax = Math.max(0, ...props.trendData.map(item => item.value));

  // Y 轴最大值 必须是 (数据最大值) 和 (推荐值) 中 较大的一个
  const logicalMax = Math.max(dataMax, props.recommendedIntake);

  // 如果最大值是 0 (所有数据都是0)，则 Y 轴只显示到 1500
  if (logicalMax === 0) {
    return props.recommendedIntake;
  }

  // 否则，在最大值上增加 10% 的缓冲
  return logicalMax * 1.5;
});
// --- 修复结束 ---

const renderChart = () => {
  if (!chartRef.value) return;
  if (chartInstance) chartInstance.dispose();
  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption({
    tooltip: {trigger: 'axis'},
    xAxis: {type: 'category', data: props.trendData.map(item => item.date)},
    yAxis: {
      type: 'value',
      axisLabel: {formatter: '{value} ml'},
      // --- 【关键修复】 3. 应用计算出的 Y 轴最大值 ---
      max: yAxisMax.value
    },
    series: [{
      name: '饮水量', type: 'bar',
      data: props.trendData.map(item => item.value),
      color: '#5470c6',
      markLine: {
        silent: true,
        symbol: 'none',
        lineStyle: {
          color: '#1E90FF',
          type: 'dashed',
        },
        data: [
          {
            yAxis: props.recommendedIntake,
            name: '推荐饮水',
          }
        ],
        label: {
          formatter: `推荐: {c} ml`,
          position: 'end',
        }
      }
    }],
    grid: {left: '3%', right: '4N%', bottom: '3%', containLabel: true}
  });
};

watch(() => [props.trendData, props.recommendedIntake], renderChart, {deep: true});

onMounted(() => {
  renderChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (chartInstance) chartInstance.dispose();
});
</script>